<template>
	<view class="qiun-columns">
			<view class="select-box">
				<sun-dropDown v-on:onSubmitAddress="onSubmitAddress"></sun-dropDown>
			</view>
			
			<view class="dates-box">
				<view class="dates f-row-between">
					
					<view class="date f-center" :style="{ width: 100 / 3 - 3 + '%' }"
					 :class="selected == 'mz' ? 'selected' : ''" @click="selected ='mz'">
						周
					</view>
					<view class="date f-center" :style="{ width: 100 / 3 - 3 + '%' }"
					 :class="selected == 'm' ? 'selected' : ''" @click="selected ='m'">
						月
					</view>
					<view class="date f-center" :style="{ width: 100 / 3 - 3 + '%' }" 
					 :class="selected == 'y' ? 'selected' : ''" @click="selected = 'y'">
						年
					</view>
				</view>
				<uni-superDates :dateTypes="['mz', 'm', 'y']" :selected="selected" v-on:onSubmit="onSubmit"></uni-superDates>
			</view>
			<view class="chart-box">
				<view class="money-block f-row-between">
					<view class="money-item f-column-WHcenter"
						v-for="(val, key, i) in resData.total"
						@click="onChartDataType(key)"
						v-if="key != 'length'"
						:style="{ backgroundImage: resData.total[key].backgroundImage, width: 100 / chartData.series.length - 10 + '%' }">
						<view class="money f-row-Wcenter">
							<label v-show="chartData.series[key][0].name != '毛利率'">￥</label>
							<label>{{ resData.total[key].numder }}</label>
							<label class="unit">{{ chartData.series[key][0].name == '毛利率' ? '%' : resData.total[key].unit }}</label>
						</view>
						<view>
							<label class="title">{{ chartData.series[key][0].name }}</label>
						</view>
					</view>
				</view>
					<view class="qiun-charts f-column-start"><canvas type="2d" canvas-id="canvasRing" id="canvasRing" class="charts" @touchstart="touchRing"></canvas></view>
				
			</view>
			<view class="retailDetails-box f-column">
				<view class="sun-tietleBox">
					<sun-tietleBox  :tietleData="'零售明细'">
					</sun-tietleBox>
				</view>
				<view :id="idTopHeight" class="table-box f-row-Wcenter" :style="{padding:tableMargin +'rpx'}">
					<!-- height="600rpx" -->
					<wyb-table
						ref="table"
						:width="'700rpx'"
						:defaultColWidth="defaultColWidth"
						:headers="headers"
						:contents="resData.list"
						:header-bg-color="'#128A80'"
						:header-ft-color="'#ffffff'"
						:loading="false"
						:first-line-fixed="false"
						:maxHeight="topHeight - (tableMargin * 2) +'rpx'"
						:url-col="urlCol"
						:min-height="[65,50]"
					/>
				</view>
			</view>
	</view>
</template>

<script>
var canvaRing = null;
import sunTietleBox from '@/components/sun-titleBox/sun-tietleBox.vue';
import sunDropDown from '@/components/sun-dropDown/sun-dropDown.vue';
import api_server from '@/api/api_server.js';
import uChart from '@/components/u-charts/u-charts.js';

import wybTable from '@/components/wyb-table/wyb-table.vue';

const theUrl = '/pages/demos/noticeBar-demo/more';
const httpUrl = 'https://ext.dcloud.net.cn/plugin?id=2667';



export default {
	components: {
		wybTable,
		sunDropDown,
		sunTietleBox
	},
	data() {
		return {
			selected: 'mz',
			//平分表宽
			defaultColWidth:167,
			//日期轮播
			background: ['color1', 'color2', 'color3'],
			indicatorDots: false,
			autoplay: false,
			interval: 2000,
			duration: 500,
			
			cWidth: '',
			cHeight: '',
			pixelRatio: 2,
			scrollTop: 0,
			//定义头部字段
			headers: [
				{
					label: '日期',
					key: 'week_day',
				},
				{
					label: '销售金额',
					key: 'sale_amt',
				},
				{
					label: '销售毛利',
					key: 'sale_ml',
				},
				{
					label: '毛利率',
					key: 'ml_rate',
				}
			],
			contents: [],

			urlCol: [
				{
					type: 'route',
					key: 'url'
				},
				{
					type: 'http',
					key: 'link'
				}
			],
			resData: {
				total: {
					sale_amt: {
						numder: 0.0,
						backgroundImage: 'linear-gradient(to top right, RGBA(151, 214, 226, 1), RGBA(85, 210, 184, 1))'
					},
					sale_ml: {
						numder: 0.0,
						backgroundImage: 'linear-gradient(to top right, rgba(141, 186, 253, 1.0), RGBA(143, 108, 244, 1))'
					},
					ml_rate: {
						numder: 0.0,
						backgroundImage: 'linear-gradient(to top right, RGBA(249, 197, 150, 1), RGBA(241, 121, 142, 1))'
					}
				},
				list: [
					{
						week_day: 1,
						month_str: '2020-08',
						sale_amt: 0.0,
						sale_ml: 0.0,
						ml_rate: 0.0
					},
				]
			},
			chartDataType: 'sale_amt',
			chartData: {
				categories: [],
				series: {
					sale_amt: [
						{
							name: '销售额',
							data: [],
							color: 'rgba(85, 170, 127, 1.0)'
						}
					],
					sale_ml: [
						{
							name: '毛利额',
							data: [],
							color: 'rgba(85, 170, 127, 1.0)'
						}
					],
					ml_rate: [
						{
							name: '毛利率',
							data: [],
							color: 'rgba(85, 170, 127, 1.0)'
						}
					]
				}
			},
			
			query: {
				dateType: 'mz',
				dateSelect: [],
				anatype:1, //分析周期 1、按周 2、按月 3、按年
				tottype:1, //数据类型 1、全部 2、线上 3、线下
				branch_jg:'', //机构 支持%为全部机构
				start_date: 10000000,
				end_date:10000000
			},
			fromData:{
				version: '1',
				pageNo: 1,
				onePageNum: 10,
			},
			//表格高度变量
			idTopHeight : 'table-box',
			tableMargin :20,
			topHeight :100
		};
	},
	onLoad() {
		this.$util.getDefaultColWidth(this, 710, 'headers', 'defaultColWidth');
		//chart
		this.cWidth = uni.upx2px(710);
		// #ifdef MP
		this.cHeight = uni.upx2px(430);
		// #endif
		// #ifndef MP
		this.cHeight = uni.upx2px(432);
		// #endif
		this.pixelRatio = uni.getSystemInfoSync().pixelRatio;
		if(this.pixelRatio > 2){
			this.pixelRatio = 2;
		}
		//获取时间

		// var date1 = '2020-01-01';
		// var date2 = '2020-12-13';
		// var date3 = new Date(date1);
		// var date4 = new Date(date2);
		// var date5 = date3.getTime();
		// var date6 = date4.getTime();
		// console.log(date5, date6);
	},

	computed: {
		userInfo() {
			var userInfo = this.$store.getters.getUserInfo;
			
			return userInfo;
		},
		chartData1() {
			//console.log(this.$util.moneyUnit(-56835));

			let query = this.query;
			if (!query.dateType) {
				return;
			}
			//清除类别总数
			for (let item in this.resData.total) {
				this.resData.total[item].number = 0;
				this.resData.total[item].unit = '';
			}
			
			
			if (query.dateType == 'mz') {
			this.chartData.categories =  ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
			}
			if (query.dateType == 'm') {
				for(var i =0,len = query.daysM.length; i<len; i++ ){
					if( query.daysM[i]%2 == 0){
						query.daysM[i] = ''
					}
				}
				this.chartData.categories = query.daysM;
			}
			if (query.dateType == 'y') {
				this.chartData.categories = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
			}

			var that = this;
			for (let item in this.chartData.categories) {
				//代表 chart X轴上的某一刻度
				item = parseInt(item);
				//清除chartData.series数据
				for (let key in this.resData.total) {
					this.chartData.series[key][0].data[item] = 0;
				}
				//根据不同的条件整理chartData.series数据
				this.resData.list.forEach(function(item1) {
					if (query.dateType == 'mz') {
						if (that.headers[0].key != 'week_day') {
							that.headers[0].key = 'week_day';
						}
						if (item + 1 == item1['week_day']) {
							item1['week_day'] = ' 周' + item1['week_day'];
							for (let key in that.resData.total) {
								that.chartData.series[key][0].data[item] = item1[key];
							}
						}
					}
					if (query.dateType == 'y') {
						if (that.headers[0].key != 'month_str') {
							that.headers[0].key = 'month_str';
						}
						
						if (item + 1 == item1['month_str'].slice(5, 7)) {
							for (let key in that.resData.total) {
								that.chartData.series[key][0].data[item] = item1[key];
							}
						}
					}
			
					if (query.dateType == 'm') {
						if (that.headers[0].key != 'jxc_date') {
							that.headers[0].key = 'jxc_date';
						}
						if (item + 1 == new Date(item1['jxc_date']).getDate()) {
							item1['jxc_date'] = query.year + '-' + query.month + '-' + new Date(item1['jxc_date']).getDate() ;
							for (let key in that.resData.total) {
								that.chartData.series[key][0].data[item] = item1[key];
							}
						}
					}
				});
			}
			
			
			//算类别总数
			for (var i = 0; i < this.resData.list.length; i++) {
				for (let key in this.resData.total) {
					this.resData.total[key].number = this.$util.floatObj.add(this.resData.total[key].number || 0, this.resData.list[i][key] || 0);
				}
				//加表格的%
				var item = this.resData.list[i];
				 item.ml_rate = item.ml_rate +'%';
			}
			for (let key in this.resData.total) {
				//算类别总数转换中文单位
				let item = this.$util.moneyUnit(this.resData.total[key].number);
				this.resData.total[key] = { ...this.resData.total[key], ...item };
			
			}
			return this.chartData;
			
		}
	},
	// mounted(){
	// 	this.$nextTick(()=>{
	// 		console.log('onReady>>>>>>1>>>>')
	// 		this.onSubmitSend();
	// 		//渲染数据
	// 		this.onChartDataType(this.chartDataType);
	// 	})
	// },
	onReady() {
		this.$nextTick(() => {
			this.onSubmitSend();
			//渲染数据
			this.onChartDataType(this.chartDataType);
		});
		this.$util.getTopHeight(this,this.idTopHeight,this.tableMargin);
	},
	methods: {
		//为了遮住chart的滚动
		scroll: function(e) {
			this.scrollTop = e.detail.scrollTop;
		},
		onChartDataType(strType) {
			//分  三中图
			this.chartDataType = strType;
			this.showRing();
		},
		//时间回调
		onSubmitSend() {
			this.$emit('onSubmitSend', false);
		},
		//处理反馈
		onSubmit(dates) {
			console.log('onSubmit>>>', dates);
			if (dates) {
				this.resData.list = [];
				this.query ={...this.query,...dates};
				
				this.login();
			}
		},
		login() {
			if(!this.query.branch_jg !=''){
				this.query.branch_name = this.userInfo.branch_name;
				this.query.branch_jg = this.userInfo.branch_default; 
			}
			let query = this.query;
			 query={...this.fromData,Params:query};   
			api_server.dwzy_GetAppMlAnalysis({
				data: query,
				success: res => {
					if (res.data.data) {
						this.resData.list = [];
						this.resData.list = res.data.data;
						this.chartData = this.chartData1;
						
						this.showRing();
						
					}
				},
				fail(error) {
					console.log('error', error);
				}
			});
		},
		
		showRing() {
			let _self = this;
			let canvasId = 'canvasRing';
			let data1 = {
				$this: _self,
				canvasId: canvasId,

				type: 'line',
				fontSize: 11,
				legend: {
					show: true,
					position: "top",
					margin : 0,
					padding : 5,
					itemGap :0,
					lineHeight : 15
				},
				dataLabel: false,
				dataPointShape: true,
				background: '#FFFFFF',
				pixelRatio: _self.pixelRatio,
				categories: _self.chartData.categories,
				series: _self.chartData.series[_self.chartDataType],
				animation: true,
				xAxis: {
					type: 'grid',
					disableGrid: true,
					gridColor: '#CCCCCC',
					gridType: 'dash',
					dashLength: 8
				},
				yAxis: {
					disableGrid: true,

					gridType: 'dash',
					gridColor: '#CCCCCC',
					dashLength: 8,
					splitNumber: 5,
					min: 10,
					max: 180,
					format: val => {
						return val.toFixed(0);
					}
				},
				width: _self.cWidth * _self.pixelRatio,
				height: _self.cHeight * _self.pixelRatio,
				extra: {
					line: {
						type: 'straight'
					}
				}
			};
			//#ifdef MP
			const query = uni.createSelectorQuery();
			query
				.select('#' + canvasId)
				.fields({ node: true, size: true })
				.exec(res => {
					const canvas = res[0].node;
					const ctx = canvas.getContext('2d');
					canvas.width = res[0].width * _self.pixelRatio;
					canvas.height = res[0].height * _self.pixelRatio;

					data1.canvas2d = true;
					data1.context = ctx;
					canvaRing = new uChart(data1);
				});
			//#endif
			//#ifndef MP
			canvaRing = new uChart(data1);
			//#endif
		},
		touchRing(e) {
			canvaRing.showToolTip(e, {
				format: function(item) {
					return item.name + ':' + item.data;
				}
			});
		},
		onSubmitAddress(e){
			this.query.branch_jg = e.address.branch_no;
			this.query.branch_name = e.address.branch_name;
			this.login();
			
		}
	}
};
</script>

<style scoped lang="scss">
.select-box {
	width: 100%;
	padding: 0 30upx;
}

.dates-box {
	background-color: #fcfdfd;
	padding: 20upx 30upx 0 30upx;
	border-radius: 15upx 15upx 0 0;
}

.chart-box {
	border-radius: 0 0 15upx 15upx;
	padding: 0 20upx;
	background-color: #fcfdfd;
	.money-block {
		width: 100%;
		padding-top: 30upx;
		border-top: 1rpx solid #d7d7d7;

		.money-item {
			width: 230upx;
			height: 160upx;
			border-radius: 10upx;
			box-shadow: 2rpx 2rpx 15rpx rgba(224, 32, 32, 0.2);
			.money {
				width: 100%;
			}
			label:nth-of-type(1) {
				height: 30upx;
				font-size: 30upx;
				font-family: Source Han Sans CN;
				font-weight: 400;
				color: #fcfdfd;
				line-height: 62upx;
			}

			label:nth-of-type(2) {
				height: 38upx;
				font-size: 40upx;
				font-family: Source Han Sans CN;
				font-weight: bold;
				color: #fcfdfd;
			}
			.unit {
				height: 38upx;
				font-size: 40upx;
				font-family: Source Han Sans CN;
				font-weight: 600;
				color: #fcfdfd;
			}
			.title {
				height: 24upx;
				font-size: 20upx;
				font-family: Source Han Sans CN;
				font-weight: 400;
				color: #fcfdfd;
			}
		}

	}
		
	
}
.qiun-charts {
	width: 710upx;
	height: 450upx;
	// #ifndef MP
	position: relative;
	// #endif
	background-color: rgba(0, 0, 0, 0);	
}
.charts { 
	height: 450upx; //小程序chart元素的高度(.qiun-charts元素外层  统一)
	// #ifdef MP
	width: 710upx; //小程序chart元素的宽度（同cWidth）（父级宽度减父级的padding宽度）
	// #endif
	// #ifndef MP
	width: 1400upx; //小程序chart元素的宽度（同cWidth）（父级宽度减父级的padding宽度）
	height: 900upx; //小程序chart元素的高度(.qiun-charts元素外层  统一)
	position: absolute;
	top: 0; 
	left: 0;
	transform: scale(0.5) translate(-50%, -50%);
	// #endif
	background-color: rgba(255, 255, 255, 1);
}
.retailDetails-box {
	border-radius: 15upx;
	background-color: #fcfdfd;
	margin-top: 25upx;

	//控制组件的缩进（外边距）
	.sun-tietleBox{
		margin: 0 20upx;
		//slot style 当前页面的样式
		// .datas {
				
		// }
	}

}

</style>
